package com.achen.controller;

import com.achen.constant.MessageConstant;
import com.achen.constant.RedisMessageConstant;
import com.achen.entity.Result;
import com.achen.pojo.Member;
import com.achen.service.MemberService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author achen
 * @create 2020-04-21 21:51
 */
@RestController
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    //通过手机号和验证码进行登录
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String validateCode = (String) map.get("validateCode"); //获取用户输入的验证码
        String telephone = (String) map.get("telephone"); //获取用户输入的手机号
        //从redis中获取缓存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //1.判断用户输入的验证码和redis缓存的验证码是否一致是否一致
        if (validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)) {
            //输入的验证码一致
            //2.根据用户输入的手机号查询该用户是否是会员
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                //如果不是会员,将用户添加到会员中去
                member = new Member();
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                //不是会员,自动完成注册(自动将当前用户信息保存到会员表)
                memberService.addMember(member);
            }
            //3.向客户端浏览器写入cookie,将用户的信息添加到cookie中,保存的是用户的手机号,用于跟踪用户
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            //设置cookie
            cookie.setPath("/"); //项目下的所有请求都会携带cookie
            cookie.setMaxAge(60 * 60 * 24 * 30); //设置cookie有效时间为30天
            response.addCookie(cookie);
            //4.将用户的信息添加到redis中(这里没用session,原因是避免集群下的session共享问题)
            String memberJson = JSON.toJSON(member).toString(); //存取的是String而不是对象(原因是反序列化时,如果对象中包含对象,会报错)
            jedisPool.getResource().setex(telephone, 60 * 30, memberJson);

            //登陆成功
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } else {
            //输入的验证码不一致
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }
}
